package com.lemon.stock.net

import com.google.gson.JsonParseException
import com.google.gson.annotations.SerializedName
import org.json.JSONException
import retrofit2.HttpException
import java.io.IOException
import java.io.InterruptedIOException
import java.net.UnknownHostException

data class ApiResponse<T>(
    @SerializedName("errorCode") var code: Int = 0,
    @SerializedName("errorMsg") var msg: String? = "",
    @SerializedName("data") var data: T? = null
){
    fun isSuccess(): Boolean{
        return code == CODE_SUCCESS && data != null
    }

    fun isSuccessIgnoreData(): Boolean{
        return code == CODE_SUCCESS
    }

    companion object {
        const val CODE_SUCCESS = 0

        const val CODE_NET_ERROR = 4000
        const val CODE_TIMEOUT = 4080
        const val CODE_JSON_PARSE_ERROR = 4010
        const val CODE_SERVER_ERROR = 5000

        fun <T> fromException(e: Throwable): ApiResponse<T> {
            return when{
                (e is HttpException) -> ApiResponse(CODE_NET_ERROR, "网络异常(${e.code()},${e.message()})")
                (e is UnknownHostException) -> ApiResponse(CODE_NET_ERROR, "网络连接失败，请检查后再试")
                (e is InterruptedIOException) -> ApiResponse(CODE_TIMEOUT, "请求超时，请稍后再试")
                (e is IOException) -> ApiResponse(CODE_NET_ERROR, "网络异常(${e.message})")
                (e is JsonParseException || e is JSONException) -> ApiResponse(CODE_JSON_PARSE_ERROR, "数据解析错误，请稍后再试")

                else -> ApiResponse(CODE_SERVER_ERROR, "")
            }

        }
    }
}
